package models

import (
	"crypto/md5"
	"encoding/hex"
	"time"

	"github.com/astaxie/beego/orm"
)

func init() {
	orm.RegisterModel(new(Record))
}

type Record struct {
	ID      int64     `orm:"column(id);pk;auto" json:"id"`
	User    *User     `orm:"rel(fk)"`
	Logtime time.Time `orm:"auto_now;type(datetime);null"`
	IP      string    `orm:"column(ip) "`
}

func CheckUserByName(name, password string) (User, bool) {
	o := orm.NewOrm()
	var (
		user User
		ok   bool
	)
	ok = false
	qs := o.QueryTable(&user).Filter("account", name)
	if err := qs.One(&user); err == nil {
		if user.Password == PasswordMD5(password) {
			ok = true
		}
	}
	return user, ok
}

func AddRecord(obj *Record) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(obj)
	return id, err
}

func PasswordMD5(password string) string {
	h := md5.New()
	h.Write([]byte(password))
	cipherStr := h.Sum(nil)
	result := hex.EncodeToString(cipherStr)
	return result
}

func GetLastRecordByUserID(userID int) Record {
	o := orm.NewOrm()
	var (
		record Record
	)
	o.QueryTable(&record).Filter("user_id", userID).RelatedSel().OrderBy("-logtime").Limit(1).One(&record)
	return record
}
